<template>
  <el-dialog
    @open="handleQuery"
    :title="dialogTitle"
    v-model="showDialog"
    left
    destroy-on-close="true"
    :append-to-body="true"
    class="drag-dialog small-padding-dialog"
    width="90%"
    @close="close"
    align-center
  >
    <el-tabs v-model="activeName" type="border-card" @tab-click="selected">
      <el-tab-pane label="视频库" name="library">
        <ContentWrap>
          <div class="demo-image__error">
            <el-checkbox-group v-model="checked" @change="selectedPicture">
              <div class="block" v-for="item in list" :key="item">
                <span class="checkbox">
                  <el-checkbox id="pictureId" :indeterminate="false" :label="item" name="id">
                    <br />
                  </el-checkbox>
                </span>
                <video-player
                  class="video-player vjs-big-play-centered videoBox"
                  :src="item.url"
                  crossorigin="Anonymous"
                  poster=""
                  controls
                  playsinline
                  :volume="0.6"
                  :playback-rates="[0.7, 1.0, 1.5, 2.0]"
                />
                <el-text class="demonstration">{{ item.name }}</el-text>
              </div>
            </el-checkbox-group>
          </div>
          <!-- 分页 -->
          <Pagination
            v-model:limit="queryParams.pageSize"
            v-model:page="queryParams.pageNo"
            :total="total"
            @pagination="getList"
          />
        </ContentWrap>
      </el-tab-pane>
<!--      <el-tab-pane label="本地上传" name="local">-->
<!--        <ContentWrap>-->
<!--          <el-upload-->
<!--            ref="upload"-->
<!--            :auto-upload="false"-->
<!--            class="upload-demo"-->
<!--            :show-file-list="false"-->
<!--            :accept="VideoFormat"-->
<!--            v-model:file-list="fileList"-->
<!--            action="#"-->
<!--            drag-->
<!--            multiple="true"-->
<!--            :on-change="handleChange"-->
<!--          >-->
<!--            <el-icon class="el-icon&#45;&#45;upload"><upload-filled /></el-icon>-->
<!--            <div class="el-upload__text">拖拽文件到这里或者<em>点击上传</em></div>-->
<!--            <div class="el-upload__tip">-->
<!--              支持格式：{{ VideoFormatStr }}，视频大小不超过{{ VideoSize }}M-->
<!--            </div>-->
<!--          </el-upload>-->
<!--          <div style="margin-top: 10px" v-if="saved">-->
<!--            <Icon icon="mdi:remove" @click="remove" />-->
<!--            <div class="block-left" id="left">-->
<!--              <el-form :model="videoForm" label-width="80px" ref="videoFormRef">-->
<!--                <el-row>-->
<!--                  <el-col :span="12">-->
<!--                    <el-form-item-->
<!--                      label="资源标题"-->
<!--                      :rules="{-->
<!--                        required: true,-->
<!--                        trigger: ['blur', 'change'],-->
<!--                        message: '请填写资源标题'-->
<!--                      }"-->
<!--                      prop="name"-->
<!--                    >-->
<!--                      <el-input v-model="videoForm.name" />-->
<!--                    </el-form-item>-->
<!--                  </el-col>-->
<!--                  <el-col :span="12">-->
<!--                    <el-form-item label="批次编号" prop="batch">-->
<!--                      <el-input v-model="videoForm.batch" />-->
<!--                    </el-form-item>-->
<!--                  </el-col>-->
<!--                </el-row>-->
<!--                <el-row>-->
<!--                  <el-col :span="12">-->
<!--                    <el-form-item label="DOI">-->
<!--                      <el-input v-model="videoForm.doi" />-->
<!--                    </el-form-item>-->
<!--                  </el-col>-->
<!--                  <el-col :span="12">-->
<!--                    <el-form-item label="视频来源">-->
<!--                      <el-input v-model="videoForm.source" />-->
<!--                    </el-form-item>-->
<!--                  </el-col>-->
<!--                </el-row>-->
<!--                <el-row>-->
<!--                  <el-col :span="12">-->
<!--                    <el-form-item label="视频标签">-->
<!--                      <el-select v-model="videoForm.label" placeholder="请选择视频标签">-->
<!--                        <el-option-->
<!--                          v-for="item in labelList"-->
<!--                          :key="item.id"-->
<!--                          :label="item.name"-->
<!--                          :value="item.id"-->
<!--                        />-->
<!--                      </el-select>-->
<!--                    </el-form-item>-->
<!--                  </el-col>-->
<!--                  <el-col :span="12">-->
<!--                    <el-form-item label="视频分类">-->
<!--                      <el-select v-model="videoForm.classify" placeholder="请选择视频分类">-->
<!--                        <el-option-->
<!--                          v-for="item in classifyList"-->
<!--                          :key="item.id"-->
<!--                          :label="item.name"-->
<!--                          :value="item.id"-->
<!--                        />-->
<!--                      </el-select>-->
<!--                    </el-form-item>-->
<!--                  </el-col>-->
<!--                </el-row>-->
<!--                <el-row>-->
<!--                  <el-col :span="12">-->
<!--                    <el-form-item label="作者">-->
<!--                      <el-input v-model="videoForm.author" />-->
<!--                    </el-form-item>-->
<!--                  </el-col>-->
<!--                  <el-col :span="12">-->
<!--                    <el-form-item label="用途">-->
<!--                      <el-input v-model="videoForm.useTo" />-->
<!--                    </el-form-item>-->
<!--                  </el-col>-->
<!--                </el-row>-->
<!--                <el-row>-->
<!--                  <el-col :span="12">-->
<!--                    <el-form-item label="发布时间">-->
<!--                      <el-date-picker-->
<!--                        v-model="videoForm.releaseTime"-->
<!--                        type="date"-->
<!--                        placeholder="请选择发布时间"-->
<!--                        :disabled-date="disabledDate"-->
<!--                      />-->
<!--                    </el-form-item>-->
<!--                  </el-col>-->
<!--                  <el-col :span="12">-->
<!--                    <el-form-item label="密级">-->
<!--                      <el-select v-model="videoForm.secret" placeholder="请选择密级">-->
<!--                        <el-option-->
<!--                          v-for="item in secretList"-->
<!--                          :key="item.value"-->
<!--                          :label="item.label"-->
<!--                          :value="item.value"-->
<!--                        />-->
<!--                      </el-select>-->
<!--                    </el-form-item>-->
<!--                  </el-col>-->
<!--                </el-row>-->
<!--                <el-row>-->
<!--                  <el-col :span="12">-->
<!--                    <el-form-item label="拍摄时间">-->
<!--                      <el-date-picker-->
<!--                        v-model="videoForm.captureTime"-->
<!--                        type="date"-->
<!--                        placeholder="请选择拍摄时间"-->
<!--                        :disabled-date="disabledDate"-->
<!--                      />-->
<!--                    </el-form-item>-->
<!--                  </el-col>-->
<!--                  <el-col :span="12">-->
<!--                    <el-form-item label="相关地点">-->
<!--                      <el-input v-model="videoForm.place" />-->
<!--                    </el-form-item>-->
<!--                  </el-col>-->
<!--                </el-row>-->
<!--                <el-row>-->
<!--                  <el-col :span="24">-->
<!--                    <el-form-item label="描述">-->
<!--                      <el-input type="textarea" v-model="videoForm.remark" />-->
<!--                    </el-form-item>-->
<!--                  </el-col>-->
<!--                </el-row>-->
<!--              </el-form>-->
<!--            </div>-->
<!--            <div class="block-right">-->
<!--              <el-progress-->
<!--                type="dashboard"-->
<!--                v-if="showProgress"-->
<!--                :percentage="percentage"-->
<!--                width="200"-->
<!--                :indeterminate="true"-->
<!--              >-->
<!--                <template #default="{ percentage }">-->
<!--                  <span class="percentage-value">{{ percentage }}%</span>-->
<!--                  <span class="percentage-label">{{ uploadTitle }}</span>-->
<!--                </template>-->
<!--              </el-progress>-->
<!--              <video-player-->
<!--                v-if="videoForm.url"-->
<!--                class="video-player vjs-big-play-centered videoBox"-->
<!--                :src="videoForm.url"-->
<!--                poster=""-->
<!--                crossorigin="Anonymous"-->
<!--                controls-->
<!--                playsinline-->
<!--                :volume="0.6"-->
<!--                :playback-rates="[0.7, 1.0, 1.5, 2.0]"-->
<!--                :height="500"-->
<!--              />-->
<!--            </div>-->
<!--          </div>-->
<!--        </ContentWrap>-->
<!--      </el-tab-pane>-->
    </el-tabs>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="define">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessageBox, FormInstance, UploadFiles, UploadProps } from 'element-plus'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'
import { VideoFormatStr, VideoSize, VideoFormat } from '@/utils/config'
import { generateUUID } from '@/utils'
import * as videoApi from '@/api/video'
import * as metaApi from '@/api/meta'

const queryFormRef = ref<any>()
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const previewList = ref([])
const initPreview = ref(0)
const showImageUploadDialogFlag = ref(false)
const videoForm = ref({})
const saved = ref(false)
const updated = ref(false)
const dialogTitle = ref('视频上传')

const fileList = ref<UploadFiles>([])
const videoHeight = ref(0)
const uploadTitle = ref('')
const showProgress = ref(true)

const labelList = ref([])

// 分块大小20MB
const chunkSize = 1024 * 1024 * 20

const videoFormRef = ref<FormInstance>()

const percentage = ref(0)

const classifyList = ref([])

const checked = ref([])
const activeName = ref('library')
const innerVisible = ref(true)

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  type: 10,
  name: null,
  size: null,
  createTime: []
})

const showDialog = ref(false)

const openSelectVideo = () => {
  showDialog.value = true
}
const close = () => {
  showDialog.value = false
}

const handleChange: UploadProps['onChange'] = async (uploadFile, uploadFiles) => {
  saved.value = true
  //uploadTitle.value = '正在计算文件MD5'
  let md5 = generateUUID()
  let fileName = uploadFile.name
  uploadFile.md5 = md5
  const fileSize = uploadFile.size || 0
  let chunkTotals = Math.ceil(fileSize / chunkSize)
  let percents = 0
  uploadTitle.value = '正在上传'
  if (chunkTotals > 1) {
    for (
      let chunkNumber = 0, start = 0;
      chunkNumber < chunkTotals;
      chunkNumber++, start += chunkSize
    ) {
      let end = Math.min(fileSize, start + chunkSize)
      // uploadFile.raw这个是element plus 中 el-upload的自己上传的文件就放在这个raw里面，可以console.log(uploadFile)看一下
      // 加 ？是因为ts语法提示“uploadFile.raw”可能为“未定义”，加了这个就不过有报错了
      const files = uploadFile.raw?.slice(start, end)
      let form = new FormData()
      form.append('chunkNumber', chunkNumber + 1)
      form.append('chunkTotal', chunkTotals)
      form.append('fileName', uploadFile.name)
      form.append('file', files)
      form.append('fileMD5', md5)
      const result = await videoApi.uploadChunk(form)
      if (result.data) {
        console.log(percents)
        percents = percents + (1 / chunkTotals).toFixed(2) * 100
        if (chunkNumber == chunkTotals - 1) {
          percents = 100
          uploadTitle.value = '上传成功'
        }
        uploadFile.percentage = percents
        percentage.value = percents
      }
    }
    let video = await videoApi.merge(md5, chunkTotals, uploadFile.size, fileName.split('.').pop())
    showProgress.value = false
    videoForm.value = video
  } else if (chunkTotals == 1) {
    let form = new FormData()
    form.append('file', uploadFile.raw)
    const result = await videoApi.upload(form)
    console.log(result)
    showProgress.value = false
    videoForm.value = result.data
  }
  videoForm.value.name = uploadFile.name
}

const getList = async () => {
  loading.value = true
  try {
    const data = await videoApi.page(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  getList()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const props = defineProps({
  dataId: String,
  fieldId: String
})

const define = async () => {
  if (activeName.value == 'local') {
    await metaApi.addVideo(props.dataId, props.fieldId, videoForm.value)
  } else if (activeName.value == 'library') {
    await metaApi.addVideo(props.dataId, props.fieldId, checked.value)
  }
  close()
  refresh()
}
const remove = () => {
  saved.value = false
  videoForm.value = {}
}

const refresh: any = inject('getList')
defineExpose({
  openSelectVideo
})
</script>
<style lang="scss" scoped>
.block-left {
  display: inline-block;
  width: 69%;
  padding: 30px 20px;
  text-align: center;
  vertical-align: top;
  border-right: solid 1px var(--el-border-color);
  box-sizing: border-box;
}

.block-right {
  display: inline-block;
  width: 29%;
  padding: 30px 20px;
  text-align: center;
  vertical-align: top;
  border-right: solid 1px var(--el-border-color);
  box-sizing: border-box;
}

.dialog-footer {
  text-align: center;
}

.body {
  margin: 0;
}

.demo-image__error .block {
  display: inline-block;
  width: 20%;
  height: 330px;
  padding: 30px 20px;
  text-align: center;
  vertical-align: top;
  border-right: solid 1px var(--el-border-color);
  box-sizing: border-box;
}

.demo-image__error .block .more {
  float: right;
  color: #8c8a8a;
}

.demo-image__error .demonstration {
  display: block;
  margin-top: 10px;
  margin-bottom: 20px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
  text-align: left;
}

.demo-image__error .datetime {
  display: block;
  margin-top: 10px;
  font-size: 14px;
  color: #666;
  text-align: left;
}

.demo-image__error .checkbox {
  display: block;
  margin-bottom: 10px;
  font-size: 14px;
  text-align: left;
}

.demo-image__error .el-image {
  width: 100%;
  height: 100%;
  max-width: 300px;
  max-height: 200px;
}

.demo-image__error .image-slot {
  display: flex;
  width: 100%;
  height: 100%;
  font-size: 30px;
  color: var(--el-text-color-secondary);
  background: var(--el-fill-color-light);
  justify-content: center;
  align-items: center;
}

.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}

.option {
  display: flex;
  float: right;
  color: #8c8e91;
  cursor: pointer;
  align-items: center;
}

.videoBox {
  width: 100%;
  max-width: 300px;
  max-height: 300px;
}
</style>
